<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.platform" placeholder="请选择下单平台" clearable>
          <el-option v-for="item in selectPlatformType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.order_sn" clearable placeholder="请输入订单编号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.name" placeholder="下单人姓名" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.mobile" placeholder="下单人手机号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.pay_status" placeholder="是否已支付" clearable>
          <el-option v-for="item in selectWhether" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.order_status" placeholder="请选择订单状态" clearable>
          <el-option v-for="item in orderStatusList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.delivery_type" placeholder="配送方式" clearable>
          <el-option v-for="item in deliveryTypeList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="创建时间" @change="changeQueryDate" end-placeholder="结束时间"> </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="bannerTypeName" width="220" label="下单人信息">
        <template #default="scope">
          <div class="ibDraggable">
            <div>下单平台：{{ scope.row.platform_name }}</div>
            <div>订单号：{{ scope.row.order_sn }}</div>
            <div>姓名：{{ scope.row.name }}</div>
            <div>手机号：{{ scope.row.mobile }}<el-button type="text" v-if="scope.row.mobile.includes('****')" :disabledbtn="disabledbtn" @click="handleViewMobile(scope.row)">查看</el-button></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="positionName" width="220" label="手机信息">
        <template #default="scope">
          <div class="ibDraggable">
            <div>品牌：{{ scope.row.brand_name }}</div>
            <div>型号：{{ scope.row.goods_name }}</div>
            <div>{{ scope.row.spec_key_name }}</div>
            <div>售价：{{ scope.row.goods_price }}元</div>
            <div v-if="scope.row.service_key_name">服务：{{ scope.row.service_key_name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="bannerTypeName" label="绑定店铺信息">
        <template #default="scope">
          <div class="ibDraggable" v-if="scope.row.bindStore !== null">
            <div>店铺：{{ scope.row.bindStore.store_name }}</div>
            <div>手机号：{{ scope.row.bindStore.store_phone }}</div>
          </div>
          <div class="ibDraggable" v-else>
            <div>--</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status_name" label="状态">
        <template #default="scope">
          <div class="ibDraggable">
            <div>状态：{{ scope.row.status_name }}</div>
            <div>配送方式：{{ scope.row.delivery_type_name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="pay_status" label="是否已支付" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.pay_status === 1 ? 'success' : scope.row.pay_status === 0 ? 'danger' : 'info'">{{ scope.row.pay_status === 1 ? "已支付" : "未支付" }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="user_note" label="用户备注" align="center"> </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center" :formatter="(row: IDirectPurchaseOrderInfoList) => handleVerifyFormatDate(row.create_time)"> </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
            <el-button v-show="[1].includes(scope.row.order_status)" type="success" link :icon="Van" @click="handleGoodsShip(scope.row)">发货</el-button>
            <el-button v-show="[2].includes(scope.row.order_status)" type="success" link :icon="EditPen" @click="handleGoodsShip(scope.row)">修改物流单号</el-button>
            <div v-show="[0].includes(scope.row.order_status)">
              <el-popconfirm placement="top" width="160" title="你确定要取消订单吗?" @confirm="handleCancelOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="Close" type="danger">取消订单</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="[2].includes(scope.row.order_status)">
              <el-popconfirm placement="top" width="160" title="你确定要收货吗?" @confirm="handleReceiptOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="EditPen" type="success">确认收货</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="[1, 2].includes(scope.row.order_status)">
              <el-popconfirm placement="top" width="160" title="你确定要申请退款吗?" @confirm="handleApplyRefund(scope.row.id)">
                <template #reference>
                  <el-button link :icon="EditPen" type="primary">申请退款</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="scope.row.order_status === 21">
              <el-popconfirm placement="top" width="160" title="你确定要同意退款吗?" @confirm="handleAgreeToRefund(scope.row.id)">
                <template #reference>
                  <el-button link :icon="CircleCheck" type="success">同意退款</el-button>
                </template>
              </el-popconfirm>
            </div>
            <el-button type="warning" link :icon="ChatDotSquare" @click="handleOrderRemark(scope.row)">平台备注</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <!-- 物流单号注弹出框 -->
    <TrackingNumberDialog :logisticsList="logisticsList" :orderStatus="orderStatus" v-model:editVisible="trackingNumberVisible" v-model:form="trackingNumberForm" @handleSuccess="handleRackingNumberSuccess" />

    <!-- 商家备注弹出框 -->
    <RemarkDialog v-model:editVisible="remarkVisible" v-model:form="sellerRemarkForm" @handleSuccess="handleRemarkSuccess" />
  </div>
</template>

<script setup lang="ts">
import TrackingNumberDialog from "@/components/rentMachineManage/directPurchaseOrderInfo/TrackingNumberDialog.vue";
import RemarkDialog from "@/components/rentMachineManage/directPurchaseOrderInfo/RemarkDialog.vue";
import { View, Close, Search, Refresh, ChatDotSquare, Van, EditPen, CircleCheck } from "@element-plus/icons-vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { HasId, ViewMode, ViewModeFilter } from "@/types/common";
import type { IDictData } from "@/types/dict";
import { useState } from "@/hooks/useState.ts";
import type { IDirectPurchaseOrderInfoList, IDirectPurchaseOrderRemark, IDirectPurchaseOrderTrackingNumber, IMobile, ISearchDirectPurchaseOrderInfo } from "@/types/rentMachineManage/directPurchaseOrderInfo";
import { getRentMobileOrderInfo, getRentOrderUserMobileInfo, putDirectMobileOrderCancelInfo, putMobileApplyRefundOrderInfo, putMobileOrderAgreeRefundInfo, putMobileOrderConfirmInfo } from "@/utils/api/rentMobileOrder";
import type { IExpressOften } from "@/types/express";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  deliveryTypeList: Array<IDictData>;
  selectPlatformType: Array<IDictData>;
  selectWhether: Array<IDictData>;
  orderStatusList: Array<IDictData>;
  logisticsList: Array<IExpressOften>;
}
const { deliveryTypeList, selectPlatformType, selectWhether, orderStatusList, logisticsList } = defineProps<Props>();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleToPrint: [ids: number[]];
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const queryDate = ref<Array<string>>([]);
const payTime = ref<Array<string>>([]);
const deliveryTime = ref<Array<string>>([]);
const total = ref(0);

const searchCondition = reactive<ISearchDirectPurchaseOrderInfo>({
  platform: "",
  order_sn: "",
  mobile: "",
  order_status: "",
  delivery_type: "",
  pay_status: "",
  is_axz: "",
  name: "",
  /* 5租机，8全款购机 */
  is_direct: "8",
  start_create_time: "",
  end_create_time: "",
  size: 10,
  current: 1
});
const tableList = ref<Array<IDirectPurchaseOrderInfoList>>([]);
const sellerRemarkForm = reactive<IDirectPurchaseOrderRemark>({
  id: 0,
  admin_note: ""
});
const trackingNumberVisible = ref(false); /* 物流单号注弹出框 */
let orderStatus = ref(0);
const trackingNumberForm = reactive<IDirectPurchaseOrderTrackingNumber>({
  id: 0,
  shipping_code: "",
  invoice_no: ""
});

const remarkVisible = ref(false); /* 商家备注弹出框 */

/* 时间更改事件 */
function changeQueryDate(data: number[]) {
  if (data !== null) {
    searchCondition.start_create_time = data[0];
    searchCondition.end_create_time = data[1];
  } else {
    searchCondition.start_create_time = "";
    searchCondition.end_create_time = "";
  }
}
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.platform = "";
  searchCondition.order_sn = "";
  searchCondition.mobile = "";
  searchCondition.order_status = "";
  searchCondition.delivery_type = "";
  searchCondition.pay_status = "";
  searchCondition.is_axz = "";
  searchCondition.name = "";
  searchCondition.start_create_time = "";
  searchCondition.end_create_time = "";

  queryDate.value = [];
  payTime.value = [];
  deliveryTime.value = [];
  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}
/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getRentMobileOrderInfo<IDirectPurchaseOrderInfoList, ISearchDirectPurchaseOrderInfo>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IDirectPurchaseOrderInfoList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IDirectPurchaseOrderInfoList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 取消订单 */
function handleCancelOrder(id: number) {
  toggleState(true);
  putDirectMobileOrderCancelInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, 4);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 修改订单状态 */
function handleChangeOrderStatus(id: number, status: number) {
  const item = tableList.value.find(item => item.id === id);
  if (!item) return;
  item.order_status = status;
  item.status_name = orderStatusList.find(s => s.dictValue == status + "")?.dictLabel || "";
}

/* 查看手机号 */
function handleViewMobile(row: IDirectPurchaseOrderInfoList) {
  toggleState(true);
  getRentOrderUserMobileInfo<IMobile, HasId>({ id: row.id })
    .then(res => {
      ElMessage.success("查询成功");
      const item = tableList.value.find(order => order.id === row.id);
      if (item) {
        item.mobile = res.result.mobile;
      }
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 平台备注 */
function handleOrderRemark(row: IDirectPurchaseOrderInfoList) {
  sellerRemarkForm.id = row.id;
  remarkVisible.value = true;
}

/* 平台备注成功回调 */
function handleRemarkSuccess() {
  remarkVisible.value = false;
}

/* 发货 */
function handleGoodsShip(row: IDirectPurchaseOrderInfoList) {
  trackingNumberForm.id = row.id;
  if (row.deliveryDoc !== null) {
    trackingNumberForm.shipping_code = row.deliveryDoc.shipping_code;
    trackingNumberForm.invoice_no = row.deliveryDoc.invoice_no;
  } else {
    trackingNumberForm.shipping_code = "";
    trackingNumberForm.invoice_no = "";
  }
  orderStatus.value = row.order_status;
  trackingNumberVisible.value = true;
}
/* 物流单号成功回调 */
function handleRackingNumberSuccess() {
  const order = tableList.value.find(order => order.id == trackingNumberForm.id);
  if (!order) return;
  if (order.deliveryDoc === null) {
    order.deliveryDoc = {
      invoice_no: trackingNumberForm.invoice_no,
      order_id: trackingNumberForm.id,
      shipping_code: trackingNumberForm.shipping_code,
      shipping_name: ""
    };
  } else {
    order.deliveryDoc.shipping_code = trackingNumberForm.shipping_code;
    order.deliveryDoc.invoice_no = trackingNumberForm.invoice_no;
  }

  handleChangeOrderStatus(trackingNumberForm.id, 2);
  trackingNumberVisible.value = false;
}

/* 确认收货 */
function handleReceiptOrder(id: number) {
  toggleState(true);
  putMobileOrderConfirmInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, 5);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 申请售后 */
function handleApplyRefund(id: number) {
  toggleState(true);
  putMobileApplyRefundOrderInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, 21);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 同意退款 */
function handleAgreeToRefund(id: number) {
  toggleState(true);
  putMobileOrderAgreeRefundInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, 22);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

getTableInfo();
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}
</style>
